package com.gjp.globalization.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created by Gjp on 2018-11-20.
 *
 * 参考地址:https：//blog.csdn.net/lwphk/article/details/41822447
 */
@RestController
public class IndexController {

    @RequestMapping("")
    public ModelAndView page(){
        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;
    }


    @Autowired
    private LocaleResolver localeResolver;

    @RequestMapping("/locale/change")
    public String setSession(HttpServletRequest request, HttpServletResponse response, String locale){
        try {
            //这两个配置任选其一,可以不加if判断删除其一 我这里是任意配置session或者cookie修改配置后不需变代码
            //<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
            if(localeResolver instanceof org.springframework.web.servlet.i18n.SessionLocaleResolver){
                String[] localeArr = locale.split("_");
                Locale l = null;
                if(localeArr.length == 1){
                    l = new Locale(localeArr[0]);
                }else{
                    l = new Locale(localeArr[0],localeArr[1]);
                }
                //设置语言
                localeResolver.setLocale(request, response, l);
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, l); //功能同上
                System.out.println("SessionLocaleResolver");
            }
            //<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
            if(localeResolver instanceof org.springframework.web.servlet.i18n.CookieLocaleResolver){
                Cookie cookie = new Cookie(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, new Locale(locale).toString());
                cookie.setMaxAge(5);
                response.addCookie(cookie);
                response.flushBuffer();
                System.out.println("CookieLocaleResolver");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }
}
